<?php

namespace App\Repository\Db;

use App\Repository\Contracts\ProvinceScoreInterface;

/**
 * @Author:: LuXiang
 * @DateTime: 2017/9/3 20:48
 */
class ProvinceScoreRepository extends Repository implements ProvinceScoreInterface
{
    protected $rules = [
        'created' => [
            'province_name' => 'required|min:2|max:16',
            'year'=>'required|integer',
            'batch'=>'required|integer',
            'score'=>'required|integer'
        ],
        'updated' => [
            'province_name' => 'required|min:2|max:16',
            'year'=>'required|integer',
            'batch'=>'required|integer',
            'score'=>'required|integer'
        ]
    ];

    protected $messages = [
        'province.required'         => "地区名称不能为空",
        'province.min'              => "地区名称最少两个字",
        'province.max'              => "地区名称最多16个字",
        'year.required'             => "年份不能为空",
        'year.integer'              => "年份必须是整数",
        'batch.required'             => "学校类别不能为空",
        'batch.integer'              => "学校类别必须是整数",
        'score.required'            => "分数不能为空",
        'score.integer'             => "分数必须是整数",
    ];

    protected function modelName()
    {
        return 'App\Model\ProvinceScore';
    }

    public function created(array $data)
    {
        $this->validate($data, 'created');

        return $this->save($data);
    }

    public function updated($id, array $data)
    {
        $this->validate($data, 'updated');

        return $this->update($data, $id, 'id');
    }

    public function lists($limit, $page, $map = [])
    {
        $query = $this->searchMap($map);
        $total = $query->count();
        $list = $query->orderBy('year', 'desc')->orderBy('batch', 'asc')
            ->simplePaginate($limit, ['province_name', 'year', 'batch', 'subject', 'score'], 'page', $page);

        return $this->simplePaginate('list', $list->items(), $total);
    }

    public function filters()
    {
        $list = [];
        $list['province'] = $this->model->groupBy('province_name')->get(['province_name'])->toArray();
        $list['year'] = $this->model->groupBy('year')->get(['year'])->toArray();
        $list['batch'] = $this->model->groupBy('batch')->get(['batch'])->toArray();
        $list['subject'] = $this->model->groupBy('subject')->get(['subject'])->toArray();

        return $list;
    }
}